<?php
class Subscription_Manager extends Model {
	
	private $_current_blogger_id;
	
	function Subscription_Manager() {
		parent::Model();
		$this->_current_blogger_id = 0;
		$this->load->library('common');
	}
	
	function SetCurrentBloggerID($blogger_id) {
		$this->_current_blogger_id = $blogger_id;
	}
	
	function _check_blogger_id() {
		if($this->_current_blogger_id == 0) {
			throw new Exception('Invalid Blogger-ID!');
		}
	}
	
	function AddSubscription($entry_id) {
		$this->_check_blogger_id();
		
		// see if entry already subscribed
		$test = $this->db->query('SELECT * FROM `nt_subscriptions` WHERE `entry_id` = ? AND `blogger_id` = ?', array($entry_id, $this->_current_blogger_id));
		if($test->num_rows() > 0) {
			return FALSE;
		}
		
		$parms = array(
			'entry_id' => $entry_id,
			'blogger_id' => $this->_current_blogger_id,
			'updated' => 0,
			'update_time' => $this->common->Now()
		);
		$this->db->insert('nt_subscriptions', $parms);
		return TRUE;
	}
	
	function RemoveSubscription($entry_id) {
		$this->_check_blogger_id();
		
		$this->db->query('DELETE FROM `nt_subscriptions` WHERE `entry_id` = ? AND `blogger_id` = ?', array($entry_id, $this->_current_blogger_id));
	}
	
	function SetEntryUpdated($entry_id, $update_time) {
		$this->db->query('UPDATE `nt_subscriptions` SET `updated` = 1, `update_time` = ? WHERE `entry_id` = ?', array($update_time, $entry_id));
	}
	
	function SetItemViewed($entry_id) {
		$this->db->query('UPDATE `nt_subscriptions` SET `updated` = 0 WHERE `entry_id` = ? AND `blogger_id` = ?', array($entry_id, $this->_current_blogger_id));
	}
	
	function ListMySubscription() {
		$qry = $this->db->query('SELECT s.`entry_id`, s.`updated`, s.`update_time`, e.`title`, e.`author_name`, e.`state`, `e`.blogger_id, b.`user_url` FROM (`nt_subscriptions` s JOIN `nt_entries` e ON s.`entry_id` = e.`id`) JOIN `nt_bloggers` b ON e.`blogger_id` = b.`id` WHERE s.`blogger_id` = ? ORDER BY s.`update_time` DESC', array($this->_current_blogger_id));
		return $qry->result();
	}
	
	// if the original entry was removed...
	function EntryRemovedAction($entry_id) {
		$this->db->query('DELETE FROM `nt_subscriptions` WHERE `entry_id` = ?', array($entry_id));
	}
	
	function EntriesRemovedAction($arr_entry_ids) {
		$str_entry_ids = implode(', ', $arr_entry_ids);
		$this->db->query('DELETE FROM `nt_subscriptions` WHERE `entry_id` IN (' . $str_entry_ids . ')');
	}
	
}
?>